package com.gdufe.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdufe.common.entity.Product;
import com.gdufe.common.feign.UserFeign;
import com.gdufe.common.utils.PageUtils;
import com.gdufe.common.utils.Query;
import com.gdufe.common.vo.ReduceStockVo;
import com.gdufe.product.dao.ProductDao;
import com.gdufe.product.service.ProductUserService;
import com.gdufe.product.vo.ProductVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;


@Service
public class ProductUserServiceImpl extends ServiceImpl<ProductDao, Product> implements ProductUserService {

    @Resource(type = UserFeign.class)
    private UserFeign userFeign;

    //防止缓存击穿
    @Cacheable(value = "product", key = "#params", sync = true)
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        int pageNum = Integer.parseInt((String) params.get("page"));
        //获取用户输入的查询条件
        String key = (String) params.get("key");
        //若条件非空，则对商品id或名字进行筛选
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("id", key).or().like("name", key);
        }
        //对上架状态的商品进行筛选
        queryWrapper.eq("up_status", 1);
        IPage<Product> page = this.page(
                new Query<Product>().getPage(params),
                queryWrapper
        );
        params.put("page", pageNum);
        return new PageUtils(page);
    }

    //对商品表单信息进行初始化
    @Override
    public ProductVo initForm(Integer id) {
        ProductVo productVo = new ProductVo();
        Product pro = this.getById(id);
        BeanUtils.copyProperties(pro, productVo);
        return productVo;
    }

    //扣减商品库存
    @Override
    @CacheEvict(value = "product",allEntries = true)
//    @Transactional
    public void reductStock(ReduceStockVo vo) {
        Product pro = this.getById(vo.getProductId());
        int stock = pro.getStock();
        pro.setStock(stock - vo.getNum());
        this.updateById(pro);
    }

}